import axios from 'axios';
import qs from 'qs';
import store from '@/store';
import router from '../router'

//全局配置
axios.defaults.baseURL = 'http://192.168.1.9:3000/api';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.timeout = 10000;

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前判断token是否存在是否过期,加载loading等.
  if (store.getters['login/getIsLogin']) {
    config.headers.common['Authorization'] = 'Bearer ' + store.getters['login/getUserInfo'].token
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // console.log(response)
  if (response.data.code == 403) {
    store._mutations['login/removeUserInfo'][0]()
    router.replace({ path: '/admin/login' })
  }
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 响应错误时,跳转不同的错误页面,或者弹出错误信息
  return Promise.reject(error);
});
//封装请求
export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params
    })
      .then(data => {
        resolve(data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

//封装post请求
export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, qs.stringify(params))
      .then(data => {
        resolve(data.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
//封装put请求
export function put (url, params) {
  return new Promise((resolve, reject) => {
    axios.put(url, params)
      .then(data => {
        resolve(data.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}
//封装delete请求
export function deletes (url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(url, { data: params })
      .then(data => {
        resolve(data.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// export const getUsers = (params) => {
//   var url = '/admin/user/search'
//   return axios.get(url, { params })
// }
// //添加用户
// export const addUser = (params) => {
//   var url = '/admin/user'
//   return axios.post(url, params)
// }

// //删除用户
// export const userDelete = (params) => {
//   var url = '/admin/user'
//   // {userId:''}
//   return axios.delete(url, { data: params })
// }
// //菜单页面
// export const getMenus = () => {
//   var url = '/admin/users'
//   return axios.get(url)
// }

